<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
    <style>
        .box{
            width: 600px;height: 600px;border: 1px solid black;position: relative;margin: auto;
        }
        .ball{
            width: 20px;height: 20px;background: pink;border-radius: 50%;position: absolute;
        }
        .block{
            width: 100px;height: 30px;background: #777;position: absolute;bottom: 0;left: 250px;
        }
    </style>
</head>
<body>
    <div class="box">
        <div class="ball"></div>
        <div class="block"></div>
    </div>
</body>
<script>
    var box=document.querySelector(".box");
    var ball=document.querySelector(".ball");
    var block=document.querySelector(".block")
    var speedX=parseInt(Math.random()*4)+3;
    var speedY=parseInt(Math.random()*3)+4;
    setInterval(function(){
        ball.style.left=ball.offsetLeft+speedX+"px";
        ball.style.top=ball.offsetTop+speedY+"px";
        if(ball.offsetLeft>=580||ball.offsetLeft<=0){
            speedX=speedX*(-1);
        }
        if(ball.offsetTop>=580||ball.offsetTop<=0){
            speedY*=-1;
        }
        if(knock(block,ball)){
            speedY*=-1;
        }
            // speedY*=-1;
            // console.log(11)
        
    },30)

    drag(block);

    function drag(node) {
        node.onmousedown = function (eve) {
            var e = eve || window.event;
            var offsetX = e.clientX - node.offsetLeft;
            var offsetY = e.clientY - node.offsetTop;
            document.onmousemove = function (eve) {
                var e = eve || window.event;
                var l = e.clientX - offsetX;
                var t = e.clientY - offsetY;
                // 限制左右出界
                if (l <= 0) 
                {l = 0}
                if (l >=500) {
                    l = 500
                }
                // 限制上下出街
                if (t <= 0) t = 0;
                if (t >= 570) {
                    t = 570
                }
                node.style.left = l + 'px';
                node.style.top = t + 'px';
            }
        }
        document.onmouseup = function () {
            document.onmousemove = null;
        }
    }
    function knock(node1,node2){
        var l1=node1.offsetLeft;
        var r1=node1.offsetLeft+node1.offsetWidth;
        var t1=node1.offsetTop; 
        var b1=node1.offsetTop+node1.offsetHeight;

        var l2=node2.offsetLeft;
        var r2=node2.offsetLeft+node1.offsetWidth;
        var t2=node2.offsetTop;
        var b2=node2.offsetTop+node1.offsetHeight;

        if(l2>r1||r2<l1||t2>b1||b2<t1){
            return false;
        }else{
            return true;
        }
    }
</script>
</html>